import axios from 'axios'
import { filterEmptyKey } from '@/utils/util.js'
import { Message } from 'element-ui'

axios.defaults.timeout = 40000
axios.tempGet = axios.get
axios.get = (url, data = {}, config = {}) => {
  return axios.tempGet(url, { params: data.params || data, ...config })
}

// 添加请求拦截器
axios.interceptors.request.use(config => {
  const noLoginUrl = [] // 不需要登录的接口地址
  if (!noLoginUrl.includes(noLoginUrl)) {
    config.headers.token = sessionStorage.getItem('token')
  }
  if (config.method === 'get' && config.params) {
    config.params = filterEmptyKey(config.params)
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(res => {
  if (res.status !== 200) {
    Message({ type: 'error', message: '数据加载失败，请稍后再试' })
    return Promise.reject(new Error(res.data))
  }
  if (Object.prototype.toString.call(res.data) !== '[object Object]') {
    Message({ type: 'error', message: '返回数据异常' })
    return Promise.reject(new Error(res.data))
  }

  if (res.data.code === 200) {
    return res.data.data
  } else if (res.data.code === 100000) {
    sessionStorage.removeItem('token')
    location.href = location.origin + '/#/login'
  } else {
    Message({ type: 'error', message: res.data.message })
  }
  return Promise.reject(res.data)
}, error => {
  Message({ type: 'error', message: error.message })
  return Promise.reject(error)
})

export default axios
